package com.yuchen.ishop.web.app.seller;

import com.yuchen.core.MyPager;
import com.yuchen.ishop.entity.Goods;
import com.yuchen.ishop.entity.GoodsHouse;
import com.yuchen.ishop.entity.GoodsImg;
import com.yuchen.ishop.entity.GoodsTemplate;
import com.yuchen.ishop.service.CacheService;
import com.yuchen.ishop.service.file.FileRequest;
import com.yuchen.ishop.service.file.FileRestClient;
import com.yuchen.ishop.service.goods.GoodsImgRestClient;
import com.yuchen.ishop.service.goods.GoodsRestClient;
import com.yuchen.ishop.service.goods.GoodsTemplateRestClient;
import com.yuchen.ishop.vo.CookieUserInfo;
import com.yuchen.ishop.vo.FileResponse;
import com.yuchen.ishop.web.BaseAction;
import com.yuchen.jaxrs.Responses;
import com.yuchen.utils.fastjson.JsonUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Controller
@RequestMapping(value = "/my/seller")
public class MyGoodsAction extends BaseAction {

    private final static Logger LOG = Logger.getLogger(MyGoodsAction.class);

    @Autowired
    private FileRestClient fileRestClient;

    @Autowired
    private GoodsImgRestClient goodsImgRestClient;

    @Autowired
    private GoodsRestClient goodsRestClient;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private GoodsTemplateRestClient goodsTemplateRestClient;


    @RequestMapping(value = {"/addGoods", "/editGoods"})
    public String add_edit_goods(Long id, ModelMap modelMap) throws Exception {
        modelMap.addAttribute("sysGoodsType", cacheService.getDictionaryCache());
        modelMap.addAttribute("myMenu", "goods");
        if (null == id)
            return "my/seller/addGoods";
        else {
            modelMap.addAttribute("goods", goodsRestClient.get(id));
            return "my/seller/editGoods";
        }
    }

    @RequestMapping(value = "/uploadGoodsImg", method = RequestMethod.POST)
    @ResponseBody
    public Responses uploadGoodsImg(Long goodsId, HttpServletRequest request) throws Exception {
        try {
            // Goods goods = new Goods();
            GoodsImg goodsImg = new GoodsImg();
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> files = multipartRequest.getFiles("file");
            if (null != files && files.size() > 0) {
                for (MultipartFile file : files) {
                    String type = FilenameUtils.getExtension(file.getOriginalFilename()).toLowerCase();
                    FileRequest req = new FileRequest(type, "goods", file.getInputStream());
                    FileResponse response = fileRestClient.sendFile(req);
                    if (response.getStatus()) {
                        goodsImg.setGoodsId(goodsId);
                        goodsImg.setImageUrl(response.getPath());
                        goodsImg.setType(0l);
                        return goodsImgRestClient.insert(goodsImg);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }

    @RequestMapping(value = "myGoods")
    public String goods(ModelMap modelMap, HttpServletRequest request) {
        modelMap.addAttribute("myMenu", "goods");
        Map params = convertParameterMap(request.getParameterMap());
        CookieUserInfo userInfo = cookie2UserInfo(request);
        if (params == null) params = new HashMap();
        String role = userInfo.getRole();
        if ("seller".equals(role))
            params.put("sellerId", userInfo.getId());
        else {
            params.put("sellerId", userInfo.getSellerId());
            params.put("xiaoerId", userInfo.getId());
        }
        MyPager myPager = goodsRestClient.finds(params);
        modelMap.addAttribute("pager", myPager);
        modelMap.addAttribute("publicState", 1);
        return "my/seller/myGoods";
    }

    @RequestMapping(value = "myGoodsNot")
    public String myGoodsNot(ModelMap modelMap, HttpServletRequest request) {
        modelMap.addAttribute("myMenu", "goods");
        Map params = convertParameterMap(request.getParameterMap());
        CookieUserInfo userInfo = cookie2UserInfo(request);
        if (params == null) params = new HashMap();
        String role = userInfo.getRole();
        if ("seller".equals(role))
            params.put("sellerId", userInfo.getId());
        else {
            params.put("sellerId", userInfo.getSellerId());
            params.put("xiaoerId", userInfo.getId());
        }
        params.put("publicState", 0);
        MyPager myPager = goodsRestClient.finds(params);
        modelMap.addAttribute("pager", myPager);
        modelMap.addAttribute("publicState", 0);
        return "my/seller/myGoodsNot";
    }


    @RequestMapping(value = "/saveGoods", method = RequestMethod.POST)
    public String saveGoods(Goods goods, String plu_imageIds, Long pageNo, Long setTemplate, String templateName, RedirectAttributes redirectAttributes) throws Exception {
        pageNo = pageNo == null ? 1l : pageNo;
        goods.setState(1l);
        //  goods.setPublishState(1l);//是否上架：0未上架  1上架
        goods.setImgIds(plu_imageIds);
        goods.setCreateTime(getTime());
        goods.setUpdateTime(getTime());
        Responses responses = goodsRestClient.insert(goods);
//        if (responses.isStatus()) { }
        if(setTemplate!=null && setTemplate==1){//模版
            GoodsTemplate template = new GoodsTemplate();
            if(StringUtils.isBlank(templateName)){
                templateName ="商品模版";
            }
            template.setTemplateName(templateName);
            BeanUtils.copyProperties(goods,template);
            BeanUtils.copyProperties(goods.getHouse(),template);
            goodsTemplateRestClient.insert(template);
        }
        if (goods.getPublishState() != null && goods.getPublishState() == 0) {
            return "redirect:/my/seller/myGoodsNot.htm?pageNo=" + pageNo;
        }
        return "redirect:/my/seller/myGoods.htm?pageNo=" + pageNo;
    }

    @RequestMapping(value = "/updateGoods", method = RequestMethod.POST)
    public String updateGoods(Goods goods, String plu_imageIds, Long pageNo, RedirectAttributes redirectAttributes) throws Exception {
        pageNo = pageNo == null ? 1l : pageNo;
//        goods.setState(1l);
//        goods.setPublishState(1l);//是否上架：0未上架  1上架
//        goods.setImgIds(plu_imageIds);
//        goods.setCreateTime(getTime());
        Responses responses = goodsRestClient.update(goods);
        /*if (responses.isStatus()) {
        }*/
        return "redirect:/my/seller/myGoods.htm?pageNo=" + pageNo;
    }

    @RequestMapping(value = "/deleteGoods", method = RequestMethod.POST)
    @ResponseBody
    public Responses deleteGoods(Long id, RedirectAttributes redirectAttributes) throws Exception {
        Responses responses = goodsRestClient.delete(id);
        if (responses.isStatus()) {
            try {
                Responses imgRes = goodsImgRestClient.showGoodsImg(id);
                List<GoodsImg> goodsImgs = JsonUtils.parseArray(imgRes.getJson(), GoodsImg.class);
                if (goodsImgs != null && goodsImgs.size() > 0) {
                    for (GoodsImg goodsImg : goodsImgs) {
                        goodsImgRestClient.delete(goodsImg.getId());
                        fileRestClient.deleteFile(goodsImg.getImageUrl());
                    }
                }
            } catch (Exception e) {
                LOG.error(e.getMessage());
            }
        }
        return responses;
    }


    @RequestMapping(value = "/offGoods", method = RequestMethod.POST)
    @ResponseBody
    public Responses offGoods(Long id) {
        return goodsRestClient.offGoods(id);
    }

    @RequestMapping(value = "/upGoods", method = RequestMethod.POST)
    @ResponseBody
    public Responses upGoods(Long id) {
        return goodsRestClient.upGoods(id);
    }

    @RequestMapping(value = "/refresh", method = RequestMethod.POST)
    @ResponseBody
    public Responses refresh(Long id) {
        return goodsRestClient.refresh(id);
    }

    @RequestMapping(value = "myTemplate")
    public String myTemplate(ModelMap modelMap, HttpServletRequest request) {
        modelMap.addAttribute("myMenu", "template");
        Map params = convertParameterMap(request.getParameterMap());
        CookieUserInfo userInfo = cookie2UserInfo(request);
        if (params == null) params = new HashMap();
        String role = userInfo.getRole();
        if ("seller".equals(role))
            params.put("sellerId", userInfo.getId());
        else {
            params.put("sellerId", userInfo.getSellerId());
            params.put("xiaoerId", userInfo.getId());
        }
        MyPager myPager = goodsTemplateRestClient.finds(params);
        modelMap.addAttribute("pager", myPager);
        return "my/seller/myTemplate";
    }

    @RequestMapping(value = "importGoods")
    public String importGoods(Long templateId,ModelMap modelMap) {
        modelMap.addAttribute("sysGoodsType", cacheService.getDictionaryCache());
        modelMap.addAttribute("myMenu", "goods");
        Goods goods = new Goods();
        GoodsHouse house = new GoodsHouse();
        GoodsTemplate template = goodsTemplateRestClient.get(templateId);
        BeanUtils.copyProperties(template,goods);
        BeanUtils.copyProperties(template,house);
        goods.setHouse(house);
        modelMap.addAttribute("goods",goods);
        return "my/seller/addGoods";
    }


    @RequestMapping(value = "deleteGoodsTemplate")
    @ResponseBody
    public Responses deleteGoodsTemplate(Long templateId,ModelMap modelMap) {
        return goodsTemplateRestClient.delete(templateId);
    }
}
